//
//  WSAlertManager.m
//  WSAlertView
//
//  Created by zhangcong on 2019/3/19.
//  Copyright © 2019年 zhangcong. All rights reserved.


#import "WSAlertManager.h"

@interface WSAlertManager()

@property (strong,nonatomic) NSMutableArray * alertArray;
@property (strong,nonatomic) NSLock * lock;

@end

@implementation WSAlertManager

+ (WSAlertManager *)shared {
    static WSAlertManager *alertManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!alertManager) {
            alertManager = [[WSAlertManager alloc] init];
            alertManager.alertArray = [[NSMutableArray alloc] init];
        }
    });
    return alertManager;
}

- (WSAlertView *)alertWithCustomView:(UIView *)contentView {
    return [self alertWithCustomView:contentView closeStyle:CloseStyleTapClose];
}


- (WSAlertView *)alertWithCustomView:(UIView *)contentView closeStyle:(CloseStyle)closeStyle {
    return [self alertWithCustomView:contentView withType:WSAlertViewStyleActionSheetDown closeStyle:closeStyle animationFinish:nil dismissHandle:nil];
}

- (WSAlertView *)alertWithCustomView:(UIView *)contentView withType:(WSAlertViewStyle)style  closeStyle:(CloseStyle)closeStyle animationFinish:(showBlock)show dismissHandle:(dismissBlock)dismiss {
    WSAlertView * view = [[WSAlertView alloc] init];
    view.closeStyle = closeStyle;
    [view show:contentView withType:style animationFinish:show dismissHandle:^{
        if (dismiss) {
            dismiss();
        }
        [self.lock lock];
        [self.alertArray removeObject:view];
        [self.lock unlock];
        NSLog(@"alertCount = %lu",(unsigned long)self->_alertArray.count);
    }];
    [self.lock lock];
    [self.alertArray addObject:view];       //添加进array 避免释放
    [self.lock unlock];
    NSLog(@"alertCount = %lu",(unsigned long)_alertArray.count);
    return view;
}

- (BOOL)existViewAlert {
    [self.lock lock];
    BOOL exist = self.alertArray.count > 0;
    [self.lock unlock];
    return exist;
}

- (void)dismissAllAlertView {
    if (self.alertArray.count > 0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.lock lock];
            [self.alertArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                if ([obj isKindOfClass:WSAlertView.class]) {
                    WSAlertView * view = (WSAlertView *)obj;
                    [view dismiss];
                }
            }];
            [self.lock unlock];
        });
    }
}

@end
